package cn.hd01.weixin;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.WXApp;
import cn.hd01.repository.entity.WXOauth;
import cn.hd01.service.WXAppService;
import cn.hd01.service.WXOauthService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.auth.AuthType;
import cn.hd01.web.util.WebConstant;
import cn.hd01.web.util.WebException;

import com.github.sd4324530.fastweixin.api.OauthAPI;
import com.github.sd4324530.fastweixin.api.UserAPI;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.GetUsersResponse;
import com.github.sd4324530.fastweixin.api.response.OauthGetTokenResponse;
import com.github.sd4324530.fastweixin.message.BaseMsg;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.github.sd4324530.fastweixin.message.req.TextReqMsg;
import com.github.sd4324530.fastweixin.servlet.WeixinSupport;
import com.github.sd4324530.fastweixin.util.SignUtil;

@Controller
@RequestMapping("/weixin")
@Auth(AuthType.OFF)
public class WeixinController extends WeixinSupport {
	private static final Logger log = LoggerFactory.getLogger(WeixinController.class);

	@Autowired
	private WXAppService appService;

	@Autowired
	private WXOauthService oauthService;

	/**
	 * 绑定微信服务器
	 *
	 * @param request
	 *            请求
	 * @return 响应内容
	 */
	@RequestMapping(path = "/bind/{domain}", method = RequestMethod.GET)
	@ResponseBody
	protected final String bind(@PathVariable("domain") String domain, HttpServletRequest request) {
		WXApp app = appService.findByDomain(domain);
		if (isLegal(request, app.getToken())) {
			return request.getParameter("echostr");
		}
		return "";
	}

	/**
	 * 微信消息交互处理
	 */
	@ResponseBody
	@RequestMapping(path = "/bind/{domain}", method = RequestMethod.POST, produces = "text/xml;charset=UTF-8")
	protected final String process(@PathVariable("domain") String domain, HttpServletRequest request) {
		WXApp app = appService.findByDomain(domain);
		if (isLegal(request, app.getToken())) {
			return processRequest(request);
		}
		return "";
	}

	@Override
	protected BaseMsg handleTextMsg(TextReqMsg msg) {
		String content = msg.getContent();
		log.debug("用户发送到服务器的内容:{}", content);
		return new TextMsg("服务器回复用户消息!");
	}

	@RequestMapping(path = "/code/{domain}", method = RequestMethod.GET)
	public String getopenid(@PathVariable("domain") String domain, @RequestParam("code") String code,
			@RequestParam("state") String state, HttpSession session) {
		try {
			WXApp app = appService.findByDomain(domain);
			OauthAPI oauthAPI = new OauthAPI(appService.getApiConfig(app));
			OauthGetTokenResponse token = oauthAPI.getToken(code);
			WXOauth wxoauth = oauthService.findByWeixinIdAndOpenId(
					app.getWeixinId(), token.getOpenid());
			if (wxoauth == null) {
				GetUserInfoResponse userInfo = oauthAPI.getUserInfo(
						token.getAccessToken(), token.getOpenid());

				wxoauth = new WXOauth();
				wxoauth.setOpenId(token.getOpenid());
				wxoauth.setWeixinId(app.getWeixinId());
				//wxoauth.setSubscribeStatus(userInfo.getSubscribe());
				//wxoauth.setSubscribeTime(new Date(userInfo.getSubscribeTime()));
				wxoauth.setNickname(Base64.encodeBase64String(userInfo.getNickname().getBytes("utf-8")));
				wxoauth.setHeadimgurl(userInfo.getHeadimgurl());
				wxoauth.setSex(userInfo.getSex());
				oauthService.save(wxoauth);
			}
			session.setAttribute(WebConstant.USER_SESSION_NAME, wxoauth);
		} catch (Exception e) {
			throw new WebException(HttpStatus.BAD_REQUEST);
		}
		return "redirect:" + state;
	}

	@RequestMapping(path = "/subscribe/{domain}", method = RequestMethod.GET)
	@ResponseBody
	public String[] subscribe(@PathVariable("domain") String domain) {
		WXApp app = appService.findByDomain(domain);
		GetUsersResponse resp = new UserAPI(appService.getApiConfig(app)).getUsers("");
		for (String openid : resp.getData().getOpenid()) {
			WXOauth wxOauth = new WXOauth();
			wxOauth.setOpenId(openid);
			wxOauth.setWeixinId(app.getWeixinId());
			wxOauth.setSubscribeStatus(1);
			oauthService.save(wxOauth);
		}

		return resp.getData().getOpenid();
	}

	protected boolean isLegal(HttpServletRequest request, String token) {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		return SignUtil.checkSignature(token, signature, timestamp, nonce);
	}
	
	@RequestMapping(path = "/success")
    public String success(Model model, @RequestParam(required=false) String msg){
		model.addAttribute("msg", msg);
	    return "weixin/success";
    }

	@Override
	protected String getToken() {
		return null;
	}
}
